package com.ikingtech.platform.service.push.websocket;

import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.push.common.Deliver;
import com.ikingtech.platform.service.push.common.DeliverResult;
import com.ikingtech.platform.service.push.common.PushRequest;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;

/**
 * @author tie yan
 */
public interface WebsocketDeliver extends Deliver {

    default DeliverResult execute(List<WebSocketSession> sessions, PushRequest pushRequest) {
        String bodyStr = Tools.Json.toJsonStr(pushRequest.getBody());
        try {
            for (WebSocketSession session : sessions) {
                session.sendMessage(new TextMessage(bodyStr));
            }
            return DeliverResult.success();
        } catch (IOException e) {
            return DeliverResult.fail(e.getMessage());
        }
    }
}
